package service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import model.Board;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

import dao.BoardDao;
import dao.RoleDao;

@Service
public class BoardService {
	@Autowired
	private BoardDao boardDao;
	@Autowired
	private RoleDao roleDao;

	public void saveOrUpdate(Board board) {
		board.setLasttime(new Date());
		if (board.getStatus().equals(2)) {
			board.setPublishtime(new Date());
		}
		if (board.getId() == null) {
			boardDao.save(board);
		} else {
			boardDao.update(board);
		}
	}

	public void delete(String ids) {
		String[] idStrs = ids.split(",");
		for (String id : idStrs) {
			Integer _id = Integer.parseInt(id);
			boardDao.delete(_id);
		}

	}

	public void publish(String ids) {
		String[] idStrs = ids.split(",");
		for (String id : idStrs) {
			Integer _id = Integer.parseInt(id);
			boardDao.publish(_id);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageList<HashMap<String, Object>> queryPage(int page, int limit,
			Integer allFlag, HashMap<String, Object> map) {
		PageList<HashMap<String, Object>> pagelist = new PageList<HashMap<String, Object>>();
		PageBounds pageBounds = new PageBounds(page, limit);
		ArrayList al = new ArrayList();
		if (allFlag != 1) {
			Integer userid = (Integer) map.get("temp");
			List<HashMap<String, Object>> roles = roleDao.getRoles(userid);
			int roleFlag = 4; // 初始最低权限
			for (int i = 0; i < roles.size(); i++) {
				Integer roleid = (Integer) roles.get(i).get("roleid");
				/* 最高权限:开发、系统 业务管理、公告管理员 */
				if (roleid.equals(1) || roleid.equals(7) || roleid.equals(8)
						|| roleid.equals(14)) {
					roleFlag = 1;
					break; // 最高权限，跳出循环
				}
				/* 市质监局 */
				else if (roleid.equals(9)) {
					roleFlag = 2;
				}
				/* 区质监局 */
				else if (roleid.equals(10)) {
					roleFlag = 3;
				}
				/* 社区管理员以及平民 */
				else {
					roleFlag = 4;
				}
			}
			if (roleFlag == 1 || roleFlag == 2) {
				al.add(1);
				al.add(2);// 状态为1，2
				map.put("status", al);
				pagelist = (PageList<HashMap<String, Object>>) boardDao
						.queryPage(pageBounds, map);
			} else {
				al.add(2); // 状态为2（已发布状态）
				map.put("status", al);
				pagelist = (PageList<HashMap<String, Object>>) boardDao
						.queryPage(pageBounds, map);
			}
		} else {
			al.add(2); // 状态为2（已发布状态）
			map.put("status", al);
			pagelist = (PageList<HashMap<String, Object>>) boardDao.queryPage(
					pageBounds, map);
		}

		return pagelist;
	}

	public Board getById(Integer id) {
		return boardDao.getById(id);
	}
}
